package com.returnlive.healthinspectioninstrument.fragment.menu;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.linktop.MonitorDataTransmissionManager;
import com.linktop.constant.BluetoothState;
import com.linktop.infs.OnBatteryListener;
import com.linktop.infs.OnDeviceVersionListener;
import com.linktop.infs.OnSPO2HResultListener;
import com.linktop.whealthService.OnBLEService;
import com.returnlive.dialoglibrary.AlertDialog;
import com.returnlive.healthinspectioninstrument.R;
import com.returnlive.healthinspectioninstrument.activity.DataDealActivity;
import com.returnlive.healthinspectioninstrument.base.BaseFragment;
import com.returnlive.healthinspectioninstrument.bean.EventBlueMessage;
import com.returnlive.healthinspectioninstrument.bean.EventMessage;
import com.returnlive.healthinspectioninstrument.constant.InstanceUrl;
import com.returnlive.healthinspectioninstrument.fragment.other.BlueDialogListFragment;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 作者： 张梓彬
 * 日期： 2017/8/28 0028
 * 时间： 上午 11:55
 * 描述： 首页
 */
public class HomePageFragment extends BaseFragment implements OnDeviceVersionListener, OnSPO2HResultListener, OnBatteryListener {
    private static final String TAG = "HomePageFragment";
    @BindView(R.id.tv_bluetooth_connect)
    TextView tvBluetoothConnect;
    private BlueDialogListFragment blueDialogListFragment;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home_page, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        EventBus.getDefault().register(this);
        manager = MonitorDataTransmissionManager.getInstance();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.lay_connect_bluetooth, R.id.lay_ecg, R.id.lay_blood_pressure, R.id.lay_blood_oxygen, R.id.lay_body_temperature})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.lay_connect_bluetooth:
               /* if (!BlueDialogListFragment.isBlueConnect) {
//                    showBlueDeceiveList();
                    connectBlue();
                    manager.setOnDeviceVersionListener(this);
                    manager.setOnBatteryListener(this);
                } else {
                    manager.disConnectBle();
                    BlueDialogListFragment.isBlueConnect = false;
                    tvBluetoothConnect.setText("点此连接");
                    Toast.makeText(getActivity(), "蓝牙已断开", Toast.LENGTH_SHORT).show();
                }*/

                break;
            case R.id.lay_ecg:
                if (BlueDialogListFragment.isBlueConnect) {
                    EventBus.getDefault().postSticky(new EventMessage("ecg"));
                    JumpActivity(DataDealActivity.class);
                } else {
                    Toast.makeText(getActivity(), "请先连接蓝牙", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.lay_blood_pressure:
                if (BlueDialogListFragment.isBlueConnect) {
                    EventBus.getDefault().postSticky(new EventMessage("blood_pressure"));
                    JumpActivity(DataDealActivity.class);
                } else {
                    Toast.makeText(getActivity(), "请先连接蓝牙", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.lay_blood_oxygen:
                if (BlueDialogListFragment.isBlueConnect) {
                    EventBus.getDefault().postSticky(new EventMessage("blood_oxygen"));
                    JumpActivity(DataDealActivity.class);
                } else {
                    Toast.makeText(getActivity(), "请先连接蓝牙", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.lay_body_temperature:
                if (BlueDialogListFragment.isBlueConnect) {
                    EventBus.getDefault().postSticky(new EventMessage("body_temperature"));
                    JumpActivity(DataDealActivity.class);
                } else {
                    Toast.makeText(getActivity(), "请先连接蓝牙", Toast.LENGTH_SHORT).show();
                }
                break;

        }


    }

    private Thread thread;
    private List<OnBLEService.DeviceSort> blueDeceiveList;

    //蓝牙连接
    private void connectBlue() {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                if (!MonitorDataTransmissionManager.getInstance().isScanning()) {
                    MonitorDataTransmissionManager.getInstance().autoScan(true);
                    while (true) {
                        blueDeceiveList = MonitorDataTransmissionManager.getInstance().getDeviceList();
                        if (blueDeceiveList.size() > 0) {
                            MonitorDataTransmissionManager.getInstance().autoScan(false);
                            Message msg = new Message();
                            msg.obj = "1";
                            blueHandler.sendMessage(msg);
                            break;
                        }
                    }
                }
            }
        });
        thread.start();


    }


    private Handler blueHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            if (result.equals("1")) {
                if (blueDeceiveList != null && blueDeceiveList.size() > 0) {
                    OnBLEService.DeviceSort deviceSort = blueDeceiveList.get(0);

                    Log.e(TAG, "蓝牙名称: "+deviceSort.bleDevice.getName());
                    Log.e(TAG, "蓝牙地址: "+deviceSort.bleDevice.getAddress());
                    getConnect(deviceSort);

//                    MonitorDataTransmissionManager.getInstance().connectToBle(deviceSort.bleDevice);
                }
            }

        }
    };

    private void showBlueDeceiveList() {
        blueDialogListFragment = new BlueDialogListFragment();
        blueDialogListFragment.show(getActivity().getFragmentManager(), "");
    }

    @Override
    public void onDeviceSoftwareVersion(String s) {
        runOnUiMothod(tvBluetoothConnect, "正在连接");
    }

    @Override
    public void onDeviceHardwareVersion(String s) {
        runOnUiMothod(tvBluetoothConnect, "蓝牙已连接");
        BlueDialogListFragment.isBlueConnect = true;
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getMessage(EventMessage eventMessage) {
        switch (eventMessage.getMsg()) {
            case BluetoothState.BLE_CLOSED:
                tvBluetoothConnect.setText("蓝牙未开启");
                break;
            case BluetoothState.BLE_OPENED_AND_DISCONNECT:
                tvBluetoothConnect.setText("等待连接");
                break;
            case BluetoothState.BLE_CONNECTING_DEVICE:
                tvBluetoothConnect.setText("正在连接");
                break;

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getMessage2(EventBlueMessage eventMessage) {
        switch (eventMessage.getMsg()) {
            case "blue":
                Log.e("TAG", "getMessage2: ");
                if (!BlueDialogListFragment.isBlueConnect) {
                    manager.setOnDeviceVersionListener(this);
                    manager.setOnBatteryListener(this);
                    connectBlue();

                } else {
                    manager.disConnectBle();
                    BlueDialogListFragment.isBlueConnect = false;
                    tvBluetoothConnect.setText("点此连接");
                    Toast.makeText(getActivity(), "蓝牙已断开", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }


    private void getConnect(final OnBLEService.DeviceSort deviceSort) {
        OkHttpUtils.post().url(InstanceUrl.BLUE_SICONNECT)
                .addParams("data",deviceSort.bleDevice.getName())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(getActivity(), getResources().getString(R.string.net_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "是否允许连接: "+response);
                if (response.equals("0")){
                    new AlertDialog(getActivity()).builder()
                            .setMsg("请使用大树授权设备！")
                            .setNegativeButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            }).show();

//                    tvBluetoothConnect.setText("不允许连接");
//                    Toast.makeText(getActivity(), "请使用大树授权设备！", Toast.LENGTH_SHORT).show();
                }else {
                    MonitorDataTransmissionManager.getInstance().connectToBle(deviceSort.bleDevice);
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onSPO2HResult(int i, int i1) {
        Log.e(TAG, "i: " + i);
        Log.e(TAG, "i1: " + i1);
    }

    @Override
    public void onSPO2HWave(int i) {
        Log.e(TAG, "onSPO2HWave: " + i);

    }

    @Override
    public void onBatteryCharging() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(), "设备充电中，请暂勿使用设备", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onBatteryQuery(final int i) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (i < 10) {
                    Toast.makeText(getActivity(), "设备电量剩余" + i + "%,请及时充电！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "设备电量剩余" + i + "%！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onBatteryFull() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(), "设备电量已充满", Toast.LENGTH_SHORT).show();
            }
        });

    }






}
